package com.dawn.module.hospital.controller.app.qrcodepay;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.framework.common.pojo.PageResult;
import com.dawn.framework.common.util.date.LocalDateTimeUtils;
import com.dawn.framework.common.util.object.BeanUtils;
import com.dawn.framework.common.util.string.StrUtils;
import com.dawn.module.hospital.controller.admin.qrcodepay.vo.QrcodePayPageReqVO;
import com.dawn.module.hospital.controller.admin.qrcodepay.vo.QrcodePayRespVO;
import com.dawn.module.hospital.controller.admin.qrcodepay.vo.QrcodePaySaveReqVO;
import com.dawn.module.hospital.controller.app.qrcodepay.vo.OrderPayReqVO;
import com.dawn.module.hospital.dal.dataobject.qrcodepay.QrcodePayDO;
import com.dawn.module.hospital.enums.BHConstants;
import com.dawn.module.hospital.enums.ErrorCodeConstants;
import com.dawn.module.hospital.model.pay.PayOrderCreateResModel;
import com.dawn.module.hospital.service.CDBPayUtils;
import com.dawn.module.hospital.service.qrcodepay.QrcodePayService;
import com.dawn.module.hospital.util.RandomUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static com.dawn.framework.common.pojo.CommonResult.success;
import static com.dawn.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;

@Tag(name = "用户 APP - 扫码支付")
@RestController
@RequestMapping("/hospital/qrcode-pay")
@Validated
public class AppQrcodePayController {

    @Resource
    private QrcodePayService qrcodePayService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/create")
    @Operation(summary = "创建扫码支付")
    public CommonResult<QrcodePayDO> createQrcodePay(@Valid @RequestBody QrcodePaySaveReqVO createReqVO) {
        String orderNumber = "QP" + RandomUtils.buildRandomStr(4);
        createReqVO.setOrderNumber(orderNumber);
        Long id = qrcodePayService.createQrcodePay(createReqVO);
        QrcodePayDO qrcodePayDO = qrcodePayService.getQrcodePay(id);
        return success(qrcodePayDO);
    }

    @PostMapping("/query")
    @Operation(summary = "获得扫码支付订单")
    public CommonResult getQrcodePay(@Valid @RequestBody QrcodePayPageReqVO pageReqVO) {
        CommonResult result = qrcodePayService.queryByOrderNumber(pageReqVO.getOrderNumber());
        return result;
    }

    @PostMapping(value = "/pay")
    @Operation(summary = "支付下单")
    public CommonResult orderPay(@Valid @RequestBody OrderPayReqVO reqVO){
        String orderNumber = reqVO.getOrderNumber();
        QrcodePayDO qrcodePayDO = qrcodePayService.getQrcodePayByOrderNumber(orderNumber);
        // 微信公众号
        if (BHConstants.PAY_CARD_WX_CODE.equals(reqVO.getPayType())) {

            Object orderObj = stringRedisTemplate.opsForValue().get("PayOrderDetails_" + orderNumber);
            if(orderObj != null) {
                String cacheOrderData = orderObj.toString();
                if (!StringUtils.isEmpty(cacheOrderData)) {
                    JSONObject prePayInfo = JSON.parseObject(cacheOrderData);
                    return CommonResult.success(prePayInfo);
                }
            }

            String orderName = qrcodePayDO.getOrderType();
            String patientId = qrcodePayDO.getPatientId();
            String patientName = qrcodePayDO.getPatientName();
            String clinicNo = qrcodePayDO.getClinicNo();
            String cardNo = qrcodePayDO.getIdCardNo();
            String registerNo = qrcodePayDO.getHisBillNos();
            String openid = qrcodePayDO.getOpenid();
            String totalCost = qrcodePayDO.getAmount().toString();

            BigDecimal totalCostB = new BigDecimal(totalCost);
            String body = CDBPayUtils.packageBody(patientId,patientName,
                    StrUtils.getStringValue(clinicNo),
                    StrUtils.getStringValue(cardNo),
                    StrUtils.getStringValue(registerNo));

            CommonResult payResult = CDBPayUtils.instance().build(CDBPayUtils.DAWN_PAY)
                    .wxJsapiPay(orderNumber, BHConstants.WEIXIN_SERVICE_ACCOUNTS.getMsg()  + "-" + orderName,
                            totalCostB.setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
                            body, openid);
            if(payResult.isError()) {
                return payResult;
            }
            JSONObject resData = (JSONObject)payResult.getData();
            PayOrderCreateResModel res = JSONObject.toJavaObject(resData,PayOrderCreateResModel.class);
            String payDataStr = res.getPayData();
            stringRedisTemplate.opsForValue().set("PayOrderDetails_"+orderNumber,payDataStr,30L, TimeUnit.MINUTES);
            JSONObject prePayInfo = JSON.parseObject(payDataStr);
            return CommonResult.success(prePayInfo);
        }

        // 支付宝小程序
        if (BHConstants.ALIPAY_MINI_APPLET.getCode().equals(reqVO.getAppType())) {

        }

        return CommonResult.error(ErrorCodeConstants.BH_ERROR.getCode(),"应用类型不正确");
    }


    @PostMapping("/page")
    @Operation(summary = "获得扫码支付分页")
    public CommonResult<PageResult<QrcodePayRespVO>> getQrcodePayPage(@Valid @RequestBody QrcodePayPageReqVO pageReqVO) {
        if(StringUtils.hasLength(pageReqVO.getBeginDate()) && StringUtils.hasLength(pageReqVO.getEndDate())){
            LocalDateTime[] times = new LocalDateTime[2];
            times[0] = LocalDateTimeUtils.parse(pageReqVO.getBeginDate());
            times[1] = LocalDateTimeUtil.parse(pageReqVO.getEndDate(),FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
            pageReqVO.setCreateTime(times);
        }
        PageResult<QrcodePayDO> pageResult = qrcodePayService.getQrcodePayPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, QrcodePayRespVO.class));
    }



}